package com.lzp.java.concurrent.lock.readwritelock;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * 测试共享锁和排它锁
 *
 * @author lzp
 * @date 2020/04/13
 */
public class ReadWriteLock {
    /**
     * 定义读写锁
     */
    private static ReentrantReadWriteLock reentrantReadWriteLock = new ReentrantReadWriteLock();
    private static ReentrantReadWriteLock.ReadLock readLock = reentrantReadWriteLock.readLock();
    private static ReentrantReadWriteLock.WriteLock writeLock = reentrantReadWriteLock.writeLock();

    public static void read() {
        readLock.lock();
        try {
            System.out.println(Thread.currentThread().getName() + "获取读锁，执行读取任务");
            TimeUnit.MILLISECONDS.sleep(100);
            System.out.println(Thread.currentThread().getName() + "读取完毕");
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            readLock.unlock();
        }
    }

    public static void write() {
        writeLock.lock();
        try {
            System.out.println(Thread.currentThread().getName() + "获取写锁，执行写入任务");
            TimeUnit.MILLISECONDS.sleep(110);
            System.out.println(Thread.currentThread().getName() + "写入完毕");
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            writeLock.unlock();
        }
    }

    public static void main(String[] args) {
        new Thread(() -> read(), "读线程1").start();
        new Thread(() -> read(), "读线程2").start();
        new Thread(() -> write(), "写线程1").start();
        new Thread(() -> write(), "写线程2").start();
    }

}
